package com.zhkj.txg.module.member.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.find.adapter.FindBannerAdapter
import com.zhkj.txg.module.member.entity.MemberProductUIEntity
import com.zhkj.txg.module.member.popup.MemberInvitePopupWindow
import com.zhkj.txg.module.member.vm.MemberCardViewModel
import com.zhkj.txg.module.product.entity.SpecPriceEntity
import com.zhkj.txg.module.product.popup.ProductSpecPopupWindow
import com.zhkj.txg.module.product.ui.WatcherActivity
import com.zhkj.txg.utils.WebViewUtils
import com.zhkj.txg.utils.WebViewUtils.addImageClickListener
import com.youth.banner.Banner
import kotlinx.android.synthetic.main.activity_member_product.*
import java.math.BigDecimal

class MemberProductActivity : ViewModelActivity<MemberCardViewModel>() {

    companion object {
        val PRODUCT_ID = "product"
        fun start(context: Context, productId: Long) {
            val intent = Intent(context, MemberProductActivity::class.java)
                .putExtra(PRODUCT_ID, productId)
            context.startActivity(intent)
        }
    }

    override fun setViewModel(): MemberCardViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleMemberProduct
    override val layoutResId: Int = R.layout.activity_member_product
    private lateinit var banner: Banner<String, FindBannerAdapter>

    private var maxScrollHeight: Int = 0
    private val productSpecPopupWindow: ProductSpecPopupWindow by lazy {
        ProductSpecPopupWindow(this, { specId, goodsNum -> // 立即购买按钮回调
            productSpecPopupWindow.dismiss()
            viewModel.memberProductLiveData.value?.response?.data?.let { product ->
                product.goods?.let { goods ->
                    // 判断是否有已选择的属性
                    val selectedSpec = goods.specPrice.find { it.id == specId }
                    // 计算选择的商品总金额
                    val totalPrice =
                        BigDecimal(selectedSpec?.price ?: goods.price).multiply(BigDecimal(goodsNum)).toString()
                    //  构造UI需要的数据
                    val uiEntity = MemberProductUIEntity(
                        goods.id, goods.goodsName, selectedSpec?.specImage ?: goods.image ?: "",
                        selectedSpec?.keyName ?: getString(R.string.default_spec_value), specId.toLong(),
                        selectedSpec?.price ?: goods.price, goodsNum, totalPrice
                    )
                    // 已经填写过邀请码，跳转支付
                    if (product.isInvite) MemberPayActivity.start(this, uiEntity, "")
                    // 未填写过邀请码，弹出输入框
                    else {
                        MemberInvitePopupWindow(this) { inviteCode: String ->
                            if (inviteCode.isNotEmpty()) viewModel.checkCode(inviteCode, uiEntity)
                            else MemberPayActivity.start(this, uiEntity, inviteCode)
                        }.showPopupWindow()
                    }
                }
            }
        }, { _, _ -> }).apply {
            viewModel.memberProductLiveData.value?.response?.data?.goods?.let {
//                setPlaceholder(it.image ?: "")
//                if (it.specPrice.isNotEmpty()) initData(it.spec, it.specPrice)
//                else setEmptyData( // 没有属性可选时，默认值
//                    SpecPriceEntity(
//                        0, "0", "默认", it.marketPrice ?: "0.0", "", it.price, it.storeCount ?: 0,
//                        if (it.images.isNullOrEmpty()) "" else it.images[0]
//                    )
//                )
            }
        }
    }


    override fun initData() {
        viewModel.memberProductDetail(intent.getLongExtra(PRODUCT_ID, 0))
    }

    @Suppress("UNCHECKED_CAST")
    override fun initUI() {
        banner = bannerMember as Banner<String, FindBannerAdapter>
        bannerMember.addBannerLifecycleObserver(this).adapter = FindBannerAdapter(this)
        WebViewUtils.initWebView(webViewMember)
        webViewMember.addImageClickListener {
            if (!it.isNullOrEmpty()) WatcherActivity.open(this, arrayListOf(it), 0)
        }
        // 设置商品名字的位置
        (tvMemberName.layoutParams as ConstraintLayout.LayoutParams).circleRadius = ScreenUtil.getScreenWidth(this) / 2
        // 设置Title的变色监听
        maxScrollHeight = ScreenUtil.getScreenWidth(this)
        scrollMember.setOnScrollChangeListener { _: NestedScrollView?, _: Int, scrollY: Int, _: Int, _: Int ->
            if (scrollY <= maxScrollHeight) {
                val alpha = scrollY.toFloat() / maxScrollHeight * 255
                titleMemberProduct.setBackgroundColor(Color.argb(alpha.toInt(), 239, 214, 184))
            } else titleMemberProduct.setBackgroundColor(Color.argb(255, 239, 214, 184))
        }
        // 购买按钮监听
        tvMemberSubmit.setOnClickListener {
            productSpecPopupWindow.setMemberChoose()
            productSpecPopupWindow.showPopupWindow()
        }
    }

    override fun initViewModel() {
        // 校验结果
        viewModel.checkResultLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.let {
                if (it.uiEntity != null && it.inviteCode != null)
                    MemberPayActivity.start(this, it.uiEntity!!, it.inviteCode!!)
            }
        })
        // 会员产品
        viewModel.memberProductLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                banner.setDatas(it.goods?.images ?: mutableListOf()).start()
                it.goods?.let { goods ->
                    tvMemberPrice.text = SpanUtil.setMoneySymbol(goods.price)
                    tvMemberName.text = goods.goodsName
                    WebViewUtils.loadFullScreenHtml(webViewMember, goods.goodsContent)
                    tvMemberSubmit.text = if (it.isMember) {
                        String.format(getString(R.string.member_invite_hint), it.reward)
                    } else getString(R.string.member_buy)
                    titleMemberProduct.setTitleTextContent(
                        if (it.isMember) getString(R.string.member_invite_title)
                        else getString(R.string.member_register)
                    )
                }
            }
        })
    }
}